package com.probos.bosnatuur.monitor;

import java.util.Date;
//import java.util.HashMap;
//import java.util.LinkedHashMap;
//import java.util.Map;
//import java.text.ParseException;
//import java.text.SimpleDateFormat;
//import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.android.maps.GeoPoint;

import android.app.Activity;
import android.app.AlertDialog;
//import android.app.DatePickerDialog;
//import android.app.Dialog;
//import android.app.TimePickerDialog;
//import android.app.TimePickerDialog.OnTimeSetListener;
//import android.content.ContentValues;
//import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
// import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
//import android.widget.Adapter;
//import android.widget.AdapterView;
//import android.widget.ArrayAdapter;
//import android.widget.Button;
//import android.widget.DatePicker;
//import android.widget.TimePicker;
//import android.widget.Toast;
//import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.EditText;
//import android.widget.SimpleCursorAdapter;
//import android.widget.Spinner;
import android.widget.TextView;

public class ElementEdit extends Activity {
	
    private EditText mTitleText;
    private EditText mBodyText;
    private TextView txtLat;
    private TextView txtLon;
    
    private Long mRowId;
    private Long mProjectId;
    private String mLocation;
    private Long mNewID;

	private Double lat = (double) 0;
	private Double lon = (double) 0;
    
    private Date mDatum;
    private String mUserName;
       
    static final int DATE_DIALOG_ID = 0;
    static final int TIME_DIALOG_ID = 1;

    public static final String PREFS_NAME = "BosNatuurPrefs"; 
    static SharedPreferences mSettings;
    SharedPreferences.Editor mEditor;
    
    private ProjectDbAdapter mDbHelper;

    private AlertDialog alert;
    private String alert_type = "";
	private EditText input;
    
    @Override
    protected void onPause() {
    	saveState();
    	mDbHelper.close();
    	super.onPause();
    }
    
    @Override
    protected void onResume() {
    	super.onResume();
    	mDbHelper.open();
    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        mSettings = getSharedPreferences(PREFS_NAME, 0); 
        mUserName = mSettings.getString("username", "");
        
        mDbHelper = new ProjectDbAdapter(this);
        mDbHelper.open();
        
        setContentView(R.layout.element_edit);
        setTitle(R.string.element_edit);

        mTitleText = (EditText) findViewById(R.id.element_name);
        mBodyText = (EditText) findViewById(R.id.element_text);

		txtLat = (TextView) findViewById(R.id.element_shape_lat);
		txtLon = (TextView) findViewById(R.id.element_shape_lon);

        mRowId = (savedInstanceState == null) ? null : (Long) savedInstanceState.getSerializable(ProjectDbAdapter.KEY_ROWID);
        if (mRowId == null) {
        	Bundle extras = getIntent().getExtras();
        	if (extras != null) {
        		if (extras.containsKey(ProjectDbAdapter.KEY_ROWID))   mRowId = extras.getLong(ProjectDbAdapter.KEY_ROWID);
            	if (extras.containsKey(ProjectDbAdapter.KEY_PROJECT)) mProjectId = extras.getLong(ProjectDbAdapter.KEY_PROJECT);
        		if (extras.containsKey(ProjectDbAdapter.KEY_SHAPE))   mLocation = extras.getString(ProjectDbAdapter.KEY_SHAPE);
        		if (extras.containsKey("new_id")) mNewID = extras.getLong("new_id");

        		// if (extras.containsKey(ProjectDbAdapter.KEY_DATE))   mDatum = (Date) extras.getSerializable(ProjectDbAdapter.KEY_DATE);
        		
        		if (mLocation != null) {        			
	    			try {
	    				// decode location-object
						JSONArray a = new JSONArray(mLocation);
						if (a.length() > 0) {
							JSONObject json = a.getJSONObject(0);
							lat = (Double)json.getDouble("lat");
							lon = (Double)json.getDouble("lon");							
						}
					} catch (JSONException e) {
						// TODO: handle exception
						e.printStackTrace();
					}
					txtLat.setText("lat: " + lat.toString());
					txtLon.setText("lon: " + lon.toString());
        		}
        		
        		
//        	} else {
//        		mDatum = new Date();
        	}
        	mDatum = new Date();
        }
       
/*
        Button confirmButton = (Button) findViewById(R.id.confirm);
        confirmButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
            	saveState();
            	setResult(RESULT_OK);
                finish();
            }
        });
        
        Button cancelButton = (Button) findViewById(R.id.cancel);
        cancelButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
            	setResult(RESULT_CANCELED);
                finish();
            }
        });
*/
        
        AlertDialog.Builder alert_builder = new AlertDialog.Builder(this);
        alert_builder.setTitle("Edit location");

		// Set an EditText view to get user input 
		input = new EditText(this);
		alert_builder.setView(input);
		
		alert_builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				String s = input.getText().toString();
				if (alert_type == "Latitude") {
					try {
						lat = Double.valueOf(s);
						txtLat.setText("lat: " + s);
					} catch (NumberFormatException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				if (alert_type == "Longitude") {
					try {
						lon = Double.valueOf(s);
						txtLon.setText("lon: " + s);
					} catch (NumberFormatException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				alert_type = "";
			}
		});

		alert_builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				// Canceled.
				alert_type = "";
			}
		});
		
		alert = alert_builder.create();

		txtLat.setOnLongClickListener(new View.OnLongClickListener() {			
			public boolean onLongClick(View v) {
				alert_type = "Latitude";
				alert.setMessage("Latitude");
				input.setText(lat.toString());
				alert.show();
				return true;
			}
		});
		
		txtLon.setOnLongClickListener(new View.OnLongClickListener() {			
			public boolean onLongClick(View v) {
				alert_type = "Longitude";
				alert.setMessage("Longitude");
				input.setText(lon.toString());
				alert.show();
				return true;
			}
		});
        
        populateFields();
    }
    
    private void populateFields() {
        /*
        if (mRowId == null) {
        	// create new element
        	Bundle extras = getIntent().getExtras();
        	if (extras != null) {
        		if (extras.containsKey(ProjectDbAdapter.KEY_SHAPE)) {
        			mLocation = extras.getString(ProjectDbAdapter.KEY_SHAPE);
        			
        			try {
        				// decode location-object
						JSONArray a = new JSONArray(mLocation);
						if (a.length() > 0) {
							JSONObject json = a.getJSONObject(0);
							lat = (Double)json.getDouble("lat");
							lon = (Double)json.getDouble("lon");							
						}
					} catch (JSONException e) {
						// TODO: handle exception
						e.printStackTrace();
					}
    				txtLat.setText("lat: " + lat.toString());
    				txtLon.setText("lon: " + lon.toString());        			
        		}
        	}
            // mDatum = new Date();
       //  } else { 
       */
    	if (mRowId != null) {
        	// edit existing element

            Cursor elm = mDbHelper.fetchElement(mRowId);
            
      		mTitleText.setText(elm.getString(elm.getColumnIndexOrThrow(ProjectDbAdapter.KEY_TITLE)));
       		mBodyText.setText(elm.getString(elm.getColumnIndexOrThrow(ProjectDbAdapter.KEY_DESCRIPTION)));
       		mLocation = elm.getString(elm.getColumnIndexOrThrow(ProjectDbAdapter.KEY_SHAPE));

			try {
				// decode location-object
				JSONArray a = new JSONArray(mLocation);
				if (a.length() > 0) {
					JSONObject json = a.getJSONObject(0);
					lat = (Double)json.getDouble("lat");
					lon = (Double)json.getDouble("lon");
				}
			} catch (JSONException e) {
				// TODO: handle exception
				e.printStackTrace();
			}
			txtLat.setText("lat: " + lat.toString());
			txtLon.setText("lon: " + lon.toString());
       		
       		// SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
       		String strDatum = elm.getString(elm.getColumnIndexOrThrow("dat_element"));
			// mDatum = dateFormat.parse(strDatum);
			
			mDatum = ProjectDbAdapter.DBStringToDate(strDatum);

       		elm.close();
        }
    }

    private void saveState() {
        String title = mTitleText.getText().toString();
        String body = mBodyText.getText().toString();
        
//    	if (!mDbHelper.isOpen()) {
//    		mDbHelper.open();
//    	}

        if (mRowId == null) {
        	int new_nr = mDbHelper.newProjectElement(mProjectId);
        	if (new_nr >= 0) {
	            long id = mDbHelper.createElement(mProjectId, new_nr, title, body, mLocation, mDatum, mUserName, mNewID);
	            if (id > 0) mRowId = id;
        	}
        } else {        	
            GeoPoint p = new GeoPoint((int) (lat*1000000), (int) (lon*1000000));            
            JSONArray a = new JSONArray();
            a.put(ProjectMap.GeoPointToJSON(p));
            mLocation = a.toString();
        	
   			mDbHelper.updateElement(mRowId, title, body, mLocation);
        }
    }
    
    @Override     
    protected void onDestroy() {
        mDbHelper.close();
        super.onDestroy();
    }
}
